package com.booktrade.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.booktrade.entity.Books;
import com.booktrade.entity.Collected;
import com.booktrade.result.Result;
import com.booktrade.service.IBooksService;
import com.booktrade.service.ICollectedService;
import com.booktrade.util.BaseContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 */
@RestController
@RequestMapping("/collection")
public class CollectionController {

    @Autowired
    private ICollectedService service;

    @Autowired
    private IBooksService bookService;


    @GetMapping
    public Result<List<Books>> getCollection() {
        Integer userId = BaseContext.getCurrentId();
        List<Collected> list = service.list(new LambdaQueryWrapper<Collected>().eq(Collected::getUserId, userId));
        List<Integer> bookIds = list.stream()
                .map(Collected::getBookId)
                .collect(Collectors.toList());
        List<Books> bookList = bookService.list(new LambdaQueryWrapper<Books>().in(Books::getId, bookIds));
        return Result.success(bookList);
    }

    @PostMapping("/hope")
    public Result hope(@RequestBody Collected collected) {
        Integer userId = BaseContext.getCurrentId();
        collected.setUserId(userId);
        if (collected.getBookId() != null && collected.getUserId() != null) {
            service.save(collected);
        }
        return Result.success();
    }

    @DeleteMapping("/{bookId}")
    public Result cancel(@PathVariable("bookId") Integer bookId) {
        Integer userId = BaseContext.getCurrentId();
        service.remove(new LambdaQueryWrapper<Collected>().eq(Collected::getUserId, userId).eq(Collected::getBookId, bookId));
        return Result.success();

    }
    @GetMapping("/{bookId}")
    public Result isCollected(@PathVariable("bookId") Integer bookId) {
        Integer userId = BaseContext.getCurrentId();
        boolean isCollected = service.exists(new LambdaQueryWrapper<Collected>().eq(Collected::getUserId, userId).eq(Collected::getBookId, bookId));
        if (isCollected) {
            return Result.success(1);
        }
        return Result.success(0);
    }



}
